package models

import (
	"github.com/UnKnwon/com"
	"github.com/astaxie/beego/orm"
	_ "github.com/mattn/go-sqlite3"
	"os"
	"path"
	"strconv"
	"time"
)

const (
	_DB_NAME        = "data/goblog.db" //数据库名字
	_SQLITE3_DRIVER = "sqlite3"        //数据库驱动
)

type Topic struct {
	Tid     int64 `orm:"pk;auto"` //主键，自增
	Url     string
	Title   string
	Content string    `orm:"type(text)"`
	Created time.Time `orm:"index;type(datetime)"`      //索引为index
	Updated time.Time `orm:"null;index;type(datetime)"` //索引为index
	Views   int64     `orm:"null;index;default(1)"`
}

func RegDB() {
	//判断数据库目录是否存在
	if !com.IsExist(_DB_NAME) {
		os.MkdirAll(path.Dir(_DB_NAME), os.ModePerm)
		os.Create(_DB_NAME)
	}
	orm.RegisterModel(new(Topic))
	orm.RegisterDriver(_SQLITE3_DRIVER, orm.DR_Sqlite)
	//设置默认驱动
	orm.RegisterDataBase("default", _SQLITE3_DRIVER, _DB_NAME, 10)
}

//获取首页文章标题URL等
func GetIndexTopic() (topic []Topic) {
	o := orm.NewOrm()
	// var topic []Topic
	// num, err := o.Raw("SELECT title,created,url FROM topic ORDER BY tid DESC LIMIT 10").QueryRows(&topic)
	// if err != nil {
	// 	fmt.Println(err)
	// }
	// fmt.Println(num, topic)
	o.QueryTable("topic").OrderBy("-tid").Limit(10).All(&topic, "title", "url", "created")
	return topic
}

//获取某个主题
func GetTopic(url string) *Topic {
	var topic Topic
	o := orm.NewOrm()
	err := o.QueryTable("topic").Filter("url", url).One(&topic)
	if err == orm.ErrMultiRows {
		return nil
	}
	if err == orm.ErrNoRows {
		return nil
	}
	return &topic
}

//添加发表
func AddTopic(url, title, content string) (ok bool) {
	o := orm.NewOrm()
	var topic Topic
	topic.Url = url
	topic.Content = content
	topic.Title = title
	topic.Created = time.Now()
	topic.Views = 1
	_, err := o.Insert(&topic)
	if err == nil {
		return true
	} else {
		return !true
	}
}

//删除某个主题
func DelTopic(tid string) (ok bool) {
	toInt64, _ := strconv.ParseInt(tid, 10, 64) //string转int
	o := orm.NewOrm()
	if _, err := o.Delete(&Topic{Tid: toInt64}); err == nil {
		return true
	} else {
		return false
	}
}

//通过ID获取主题
func GetTopicById(tid string) *Topic {
	toInt64, _ := strconv.ParseInt(tid, 10, 64) //string转int
	var topic Topic
	o := orm.NewOrm()
	err := o.QueryTable("topic").Filter("tid", toInt64).One(&topic)
	if err == orm.ErrMultiRows {
		return nil
	}
	if err == orm.ErrNoRows {
		return nil
	}
	return &topic
}

//修改主题
func ModifyTopic(tid, title, content, url string) {
	o := orm.NewOrm()
	toInt64, _ := strconv.ParseInt(tid, 10, 64) //string转int
	topic := Topic{Tid: toInt64}
	if o.Read(&topic) == nil {
		topic.Title = title
		topic.Updated = time.Now()
		topic.Url = url
		topic.Content = content
		o.Update(&topic)
	}
}
